package sivan.letcode;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 滑动窗口算法
 */
public class SlidingWindows {

    private long window;
    //窗口的size 用于计算总的流量上限
    private long size;

    private AtomicLong count;

    private Long current;

    public SlidingWindows(long window, long size) {
        this.window = window;
        this.size = size;
        this.count = new AtomicLong(0);
    }

    public Boolean tryRate() {
        Long now = System.currentTimeMillis();
        if (current == null) {
            current = now;
            count.incrementAndGet();
            return true;
        } else {
            if (now - current > window) {
                current = now;
                count.set(0);
            } else {
                if (count.getAndIncrement() < size) {
                    current = now;
                    System.out.println("time: " + count.get());
                    return true;
                }
            }
        }
        return false;
    }
}
